package com.sihai.ehr.web.action.user;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.Duty;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.Resource;
import com.sihai.ehr.model.sys.Role;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.ResourceService;
import com.sihai.ehr.service.RoleService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.RolePojo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * author: wxn
 * since: 13-2-4 Time: 上午11:18
 */
@Results({@Result(name = "main", location = "/WEB-INF/pages/user/role_main.jsp"),
        @Result(name = "list", location = "/WEB-INF/pages/user/role_list.jsp"),
        @Result(name = "add", location = "/WEB-INF/pages/user/role_add.jsp"),
        @Result(name = "edit", location = "/WEB-INF/pages/user/role_modify.jsp"),
        @Result(name = "resource-list", location = "/WEB-INF/pages/user/resource_list.jsp")
})
public class RoleAction extends EHRAction {
    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private DutyService dutyService;
    @BeanInject
    private RoleService roleService;
    @BeanInject
    private ResourceService resourceService;

    private List<Organization> organizations;
    private LimitedList<RolePojo> rolePojos;
    private LimitedList<Role> roles;
    private LimitedList<Resource> resources;
    private LimitedList<Duty> dutys;
    private Role role;
    private String result;

    @Override
    @Action("/authority/role_main")
    public String execute() throws Exception {
        this.listAction = "/authority/role_list.xhtml";
        this.listTitle = "角色设置";

        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        return "main";
    }

    @Action("/authority/role_list")
    public String list() throws Exception {
        //roles = roleService.find(role, createLimit(), createSorter());
        rolePojos = roleService.findByTopOrganization(organizationId, createLimit(), createSorter());
        //分页
        this.setPageUrl("authority/role_list.xhtml");
        this.paging(rolePojos);
        resources = resourceService.find(null, null, null);
        return "list";
    }

    @Action("/authority/role_input")
    public String toInput() throws Exception {
        dutys = dutyService.findForRole(organizationId, null, null);
        if(role != null && role.getId() != null){//edit
            role = roleService.getRole(role.getId());
        }
        return "add";
    }
    //@Deprecated
    @Action("/authority/role_save")
    public String save() throws Exception {
        String[] userIds = StringUtils.split(getParameter("user_ids"), ",");
        String[] resourceIds = StringUtils.split(getParameter("resource_ids"), ",");
        List<User> userList = new ArrayList<User>();
        List<Resource> resourceList = new ArrayList<Resource>();
        if(userIds != null && userIds.length > 0){
            for(String userId : userIds){
                User user = new User();
                user.setId(NumberUtils.createLong(userId));
                userList.add(user);
            }
        }
        if(resourceIds != null && resourceIds.length > 0){
            for(String resourceId : resourceIds){
                Resource resource = new Resource();
                resource.setId(NumberUtils.createLong(resourceId));
                resourceList.add(resource);
            }
        }

        if(role != null){//edit
            //role.setUsers(userList);
            role.setResources(resourceList);
            roleService.save(role);
        }
        return execute();
    }

    @Action(value = "/authority/role-save", results = {@Result(name = "success", type = "json", params = {"root", "result"})})
    public String saveRole() throws Exception {
        String roleIdStr = getParameter("current_role_id");
        Role r = null;
        if(StringUtils.isBlank(roleIdStr)){
            Long dutyId = NumberUtils.createLong(getParameter("current_duty_id"));
            r = new Role();
            Duty d = dutyService.get(dutyId);
            if(d == null){
                result = "duty_not_exist";
                return SUCCESS;
            }
            r.setDuty(d);
        }
        else{
            Long roleId = NumberUtils.createLong(roleIdStr);
            r = roleService.getRole(roleId);
            if(r == null){
                result = "role_not_exist";
                return SUCCESS;
            }
        }
        String[] resourceIds = StringUtils.split(getParameter("resource_ids"), ",");
        List<Resource> resourceList = new ArrayList<Resource>();
        if(resourceIds != null && resourceIds.length > 0){
            for(String resourceId : resourceIds){
                Resource resource = new Resource();
                resource.setId(NumberUtils.createLong(resourceId));
                resourceList.add(resource);
            }
        }
        r.setResources(resourceList);
        roleService.save(r);
        result = "success";
        return SUCCESS;
    }


    @Action("/authority/init-resource")
    public String initResource() throws Exception {
        String webRootPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
        String templatePath = String.format("%s/resources.xls", webRootPath);
        File file = new File(templatePath);
        resourceService.initResource(file);
        return "add";
    }
    @Action("/authority/resource-list")
    public String resourceList() throws Exception {
        resources = resourceService.find(null, null, null);
        //this.setPageUrl("authority/resource-list.xhtml");
        //this.paging(resources);
        return "resource-list";
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public LimitedList<Role> getRoles() {
        return roles;
    }

    public LimitedList<Duty> getDutys() {
        return dutys;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public LimitedList<Resource> getResources() {
        return resources;
    }

    public LimitedList<RolePojo> getRolePojos() {
        return rolePojos;
    }

    public String getResult() {
        return result;
    }
}
